/*
 * Copyright (C) 2011  Xu Haojie
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.poemcode.gzlib.search;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import net.poemcode.gzlib.common.CommonThread;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class SearchThread extends CommonThread {
	
	public static final int MSG_SEARCH_ID = 0;
	
	private static final String TAG = "SearchThread";
	
	public SearchThread(Handler handler, SearchRequest request) {
		super(handler, request);
	}

	@Override
	public void run() {
		Message msg = mHandler.obtainMessage(SearchThread.MSG_SEARCH_ID);
		
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(BASE_URL);
		post.setEntity(getHttpEntity(mRequest.getHttpParamemters()));
		HttpParams params = post.getParams();
		params.setParameter("Content-Type", "application/x-www-form-urlencoded");
		post.setParams(params);
		
		HttpResponse response;
		try {
			response = client.execute(post);
		} catch (ClientProtocolException e) {
			Log.e(TAG, e.getMessage());
			msg.sendToTarget();
			return;
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
			msg.sendToTarget();
			return;
		}
		
		SearchHandler handler = new SearchHandler();
		SAXParserFactory spf = SAXParserFactory.newInstance();
		XMLReader xr;
		try {
			SAXParser sp = spf.newSAXParser();
			xr = sp.getXMLReader();
		} catch (ParserConfigurationException e) {
			Log.e(TAG, e.getMessage());
			msg.sendToTarget();
			return;
		} catch (SAXException e) {
			Log.e(TAG, e.getMessage());
			msg.sendToTarget();
			return;
		}
		
		xr.setContentHandler(handler);

		int status = response.getStatusLine().getStatusCode();
		if (status == HttpStatus.SC_OK) {
			try {
				xr.parse(new InputSource(response.getEntity().getContent()));
			} catch (IllegalStateException e) {
				Log.e(TAG, e.getMessage());
				msg.sendToTarget();
				return;
			} catch (IOException e) {
				Log.e(TAG, e.getMessage());
				msg.sendToTarget();
				return;
			} catch (SAXException e) {
				Log.e(TAG, e.getMessage());
				msg.sendToTarget();
				return;
			}
		}
		
		List<SearchResult> result = handler.getSearchResults();
		msg.obj = result;
		msg.arg1 = handler.getTotalPageSize();
		msg.sendToTarget();
	}

	private HttpEntity getHttpEntity(List<NameValuePair> paramemters) {
		UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(paramemters, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return null;
		}
		return entity;
	}
}
